using Digitalmes.Common.Interfaces;
using Digitalmes.Domain.Entities.Mes.Equipments;

namespace Digitalmes.Application.Mes.Equipments.InspectManuals.Commands;

/// <summary>
/// 手动点检命令。
/// </summary>
/// <param name="Input">手动点检数据参数</param>
public sealed record ManualInspectCommand(ManualInspectInput Input) : IRequest<IResult<bool>>;

internal sealed class ManualInspectCommandHandler(
    IRepository<EquipInspectionPlan> planRepo,
    IRepository<EquipInspectionRecord> recordRepo,
    ICurrentUser currentUser) : IRequestHandler<ManualInspectCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(ManualInspectCommand request, CancellationToken cancellationToken)
    {
        // 点检项不能重名
        var plan = await planRepo.AsQueryable()
            .Includes(m => m.Machinery, t => t!.Workstation)
            .Includes(m => m.ManualInspectionItems)
            .Where(m => m.Id == request.Input.PlanId)
            .FirstOrDefaultAsync(cancellationToken);
        if (plan == null)
        {
            return Result.Failure("没有找到点检计划");
        }

        // 新增设备点检记录
        EquipInspectionRecord inspectionRecord = new()
        {
            PlanId = plan.Id,
            MachineryId = plan.MachineryId,
            MachineryCode = plan.Machinery!.MachineryCode,
            MachineryName = plan.Machinery.MachineryName,
            InspectType = InspectTypeEnum.Manual,
            LineId = plan.Machinery.LineId,
            WorkstationId = plan.Machinery.WorkstationId,
            WorkstationCode = plan.Machinery.Workstation?.WsCode,
            StandardPartNo = request.Input.PartNo,
            InspectionTime = DateTime.Now,
            Inspector = currentUser.Username,
            Result = QualifiedEnum.Qualified,
            Data = [],
        };

        if (plan.ManualInspectionItems != null && request.Input.Data != null)
        {
            foreach (var item in plan.ManualInspectionItems)
            {
                var data = request.Input.Data.FirstOrDefault(s => s.InspectionItemId == item.Id);
                if (data != null)
                {
                    EquipInspectionData archive = new()
                    {
                        SubjectName = item.SubjectName,
                        Standard = item.Standard,
                        Value = data.Value,
                        Result = data.Result,
                        Remark = data.Remark,
                    };

                    inspectionRecord.Data.Add(archive);
                }
            }
        }

        // 是否检测最终结果，不检查默认为 OK；检查时按最严重的程度来判定
        if (plan.IsCheckFinalResult)
        {
            if (inspectionRecord.Data.Any(s => s.Result is InspectResultEnum.OOS))
            {
                inspectionRecord.Result = QualifiedEnum.Unqualified;
            }
        }

        // 导航新增
        await recordRepo.Context.InsertNav(inspectionRecord).Include(m => m.Data).ExecuteCommandAsync();

        return Result.Success();
    }
}
